package com.itcoon.cloud.framework.listener;/**
 * @author Athric Yu
 * 2024/11/26
 **/

import com.itcoon.cloud.framework.model.BootstrapTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationStartedEvent;

import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 *
 *
 * @author Athric Yu
 * 2024/11/26
 **/
public class ApplicationListener implements org.springframework.context.ApplicationListener<ApplicationStartedEvent> {

    private static final Logger log = LoggerFactory.getLogger(ApplicationListener.class);

    private final List<BootstrapTask<?>> tasks;

    public ApplicationListener(List<BootstrapTask<?>> tasks) {
        this.tasks = tasks;
    }

    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        CompletableFuture<?>[] futureArray = new CompletableFuture<?>[tasks.size()];
        for (int i = 0; i < tasks.size(); i++) {
            futureArray[i] = tasks.get(i).get();
        }
        CompletableFuture.allOf(futureArray).whenComplete((res, throwable)->{
            log.info("All bootstrap tasks completed");
            if(throwable != null){
                log.error("Application raise an exception in starting, it's message={}", throwable.getMessage());
                throw new RuntimeException(throwable.getMessage());
            }
        }).join();
    }
}
